//
//  WBMainViewController.swift
//  weibo
//
//  Created by 长城 on 16/12/8.
//  Copyright © 2016年 dhsr. All rights reserved.
//

import UIKit
///主控制器
class WBMainViewController: UITabBarController {

    //定时器 
    var timer : Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        
        //测试未读数量
        setupTimer()
    }
    /// 使用代码控制设备的屏幕方向，可以在需要横屏时单独处理！
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
            return .portrait
    }
    //MARK:-监听方法
    //FIXME:-没有实现
    func composeStatus(){
        print("撰写微博")
        
        //测试方向旋转
//        let vc = UIViewController()
//        vc.view.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
//        present(vc, animated: true, completion: nil)
    }
    //MARK:-私有控件
    lazy var composeButton:UIButton = UIButton(type:.contactAdd)
    
    deinit {
        timer?.invalidate()
    }
    
}
//extension 类似于OC中的分类，在swift中还可以用来切分代码
//可以把相近功能的函数，放在一个extension中

//MARK:-设置界面
extension WBMainViewController{
    //设置按钮
     func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少，能够让宽度变大，盖住容错点，防止穿帮
        let w = tabBar.bounds.width / count - 1
            composeButton.backgroundColor = #colorLiteral(red: 0.1960784346, green: 0.3411764801, blue: 0.1019607857, alpha: 1)
            composeButton.setBackgroundImage(UIImage(named:"tabbar_compose_button_add")?.withRenderingMode(.alwaysOriginal), for: .normal)
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        //按钮监听方法
        composeButton.addTarget(self, action:#selector(composeStatus),for:.touchUpInside)
    }
    
    //设置所有子控制器
    func setupChildControllers(){
        //获取沙盒的json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")

        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有内容，如果没有说明本地沙盒没有文件
        if data == nil{
            //从bundle加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        //data一定会有内容,反序列化
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String:AnyObject]] else{
            return
        }
        
        
        /*let array :[[String:AnyObject]] = [
                ["clsName":"WBHomeViewController" as AnyObject,"title":"首页" as AnyObject,"imageName":"home" as AnyObject,
                    "visitorInfo" : ["imageName" : "","message":"关注一些人，回这里看看有什么惊喜"] as AnyObject],
                ["clsName":"WBMessageViewController" as AnyObject,"title":"消息" as AnyObject,"imageName":"message" as AnyObject,
                 "visitorInfo" : ["imageName" : "visitordiscover_image_message","message":"还未登录，登录后获取更多信息"] as AnyObject],
                ["clsName":"UIViewController" as AnyObject],
                ["clsName":"WBDiscoverViewController" as AnyObject,"title":"发现" as AnyObject,"imageName":"discover" as AnyObject,
                 "visitorInfo" : ["imageName" : "visitordiscover_image_message","message":"还未登录，登录后体验更多精彩"] as AnyObject],
                ["clsName":"WBProfileViewController" as AnyObject,"title":"我" as AnyObject,"imageName":"profile" as AnyObject,
                 "visitorInfo" : ["imageName" : "visitordiscover_image_profile","message":"还未登录，登录后查看个人信息"] as AnyObject]
        ]
        //数组转换成json ,序列化 
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData).write(toFile: "Users/changcheng/Desktop/demo.json", atomically: true)*/
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典[clsName,title,imageName,"visitorInfo"]
    /// - Returns: 子控制器
    private func controller(dict:[String:AnyObject])->UIViewController{
        
      //1.取得字典内容
       guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String:String]
        else {
            return UIViewController()
        }
      //2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        let nav = WBNavigationController(rootViewController: vc)
        //设置控制器的访客信息字典
        vc.visitorInfoDict = visitorDict
      //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
      //4.设置tabbar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:#colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 16)], for: .normal)
        return nav
        
    }
    
    
}

// MARK: - 时钟相关方法
extension WBMainViewController{
    func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    func updateTimer(){
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("新微博数量为\(count)")
            //设置tabbaritem 的 badgeNumber
            self.tabBar.items?[1].badgeValue = count>0 ?"\(count)" : nil
            
            //设置app的 badgeNumber,在ios8.0以后要有用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}
